package com.zh.note.huawei.onehundred.计算最接近的数;

import java.util.Arrays;
import java.util.Scanner;

/**
 * https://dream.blog.csdn.net/article/details/131510440
 * 数组、模拟
 * [50,50,2,3],2
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // String input = sc.nextLine();
        String input = "[50,50,2,3],2";
        String s = input.replaceAll("[\\[\\]\\s]", "");
        String[] split = s.split(",");
        int n = split.length;
        int[] nums = new int[n - 1];
        int k = Integer.parseInt(split[n - 1]);
        for (int i = 0; i < nums.length; i++) {
            nums[i] = Integer.parseInt(split[i]);
        }
        // 找到中位数
        int mid = findMedian(nums);
        //
        int min = Integer.MAX_VALUE;
        int index = -1;
        //模拟计算过程
        for (int i = 0; i < n - k; i++) {
            int count = nums[i];
            for (int j = i + 1; j < k + i; j++) {
                count -= nums[j];
            }
            int distance = Math.abs(count - mid);
            if (distance < min) {
                min = distance;
                index = i;
            }
        }
        System.out.println(index);
    }

    private static int findMedian(int[] nums) {
        // 复制出新数组
        int[] newArr = Arrays.copyOf(nums, nums.length);
        Arrays.sort(newArr);
        return newArr[newArr.length / 2];

    }
}
